//
//  LoginViewController.m
//  Yihubang
//
//  Created by hyu on 16/7/29.
//  Copyright © 2016年 jinghao. All rights reserved.
//

#import "PreLoginViewController.h"
#import "PreLoginViewModel.h"
#import "UMSocial.h"
@interface PreLoginViewController (){
    UIImageView *navBarHairlineImageView;
}
@property (weak, nonatomic) IBOutlet UITextField *telePhone;
@property (weak, nonatomic) IBOutlet UIButton *getCode;
@property (weak, nonatomic) IBOutlet UITextField *codeText;
@property (weak, nonatomic) IBOutlet UIButton *LoginTo;
@property (weak, nonatomic) IBOutlet UIButton *weixinButton;
@property (weak, nonatomic) IBOutlet UIButton *qqButton;
@property (weak, nonatomic) IBOutlet UILabel *certifyLabel;
@property (nonatomic,strong)PreLoginViewModel *viewModel;

@property (nonatomic, weak) IBOutlet UIButton *btn;

@end

@implementation PreLoginViewController
@synthesize viewModel = _viewModel;

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.viewModel.title = @"登录";
//    [self.navigationItem setLeftBarButtonItem:[[UIBarButtonItem alloc]
//                                initWithImage:[UIImage imageNamed:@"BackNormal"]
//                                        style:UIBarButtonItemStylePlain
//                                       target:self
//                                       action:@selector(disMissAction)]
//                                     animated:TRUE];
    [self.navigationController.navigationBar setHidden:YES];
    self.telePhone.maxLenght = 11;
    self.codeText.maxLenght = 4;
//    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(200, 500, 100, 30)];
//    lable.backgroundColor = [UIColor redColor];
//    
//    [self.view addSubview:lable];

    [_btn setTitle:@"测试接口" forState:UIControlStateNormal];
    [_btn addTarget:self action:@selector(ceshijiekou) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:_btn];
}


//[[self.getCode
//  rac_signalForControlEvents:UIControlEventTouchUpInside]
// subscribeNext:^(id x) {
//     @strongify(self)
//     [self.viewModel.phoneCodeCommand execute:nil];
// }];


//self.phoneCodeCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
//    @strongify(self);
//    [[self.httpService sendPhoneCode:self.telePhoneStr resultClass:nil] subscribeNext:^(BaseModel *model) {
//        @strongify(self);
//        [self startTimer];
//        if (model.code==200) {
//            //                self.codeStr = model.data[@"code"];
//            //                [self.viewController hiddenHUDWithString:model.data[@"code"] error:NO];
//            //                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"验证码"
//            //                                                                    message:model.data[@"code"]
//            //                                                                   delegate:self
//            //                                                          cancelButtonTitle:@"知道了" otherButtonTitles: nil];
//            //                [alertView show];
//            
//        }else{
//            [self showRequestErrorMessage:model];
//        }
//    } error:^(NSError *error) {
//        [self.viewController hiddenHUDWithString:@"网络链接差,请稍候在试." error:NO];
//    } completed:^{
//        
//    }];
//    
//    return [RACSignal empty];
//}];
- (void)ceshijiekou
{
    [[self.btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        [self.viewModel.ceshi execute:nil];
    }];
    
    
    NSLog(@"测试一下");
}


//-(void)disMissAction{
//    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (self.userClient.password.length ==4) {
        [self.LoginTo setTitle:@"下一步" forState:UIControlStateNormal];
    }else{
        [self.LoginTo setTitle:@"立即进入" forState:UIControlStateNormal];
    }
    
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}


-(void) viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
}
- (void)bindViewModel
{
    [super bindViewModel];
    
    //绑定数据
    RAC(self.viewModel, telePhoneStr) = self.telePhone.rac_textSignal;
    RAC(self.viewModel, codeStr) = self.codeText.rac_textSignal;
    
    @weakify(self);
    
    //判断登录按钮是否可以用
    RAC(self.LoginTo, enabled) = self.viewModel.validLoginSignal;
    [self.viewModel.validLoginSignal
    subscribeNext:^(NSNumber * usernameIsValid) {
        @strongify(self);
        if(usernameIsValid.boolValue){
            [self.LoginTo setBackgroundColor:[UIColor colorWithHex:0xffffff alpha:1.0]];
        }else{
            [self.LoginTo setBackgroundColor:[UIColor colorWithHex:0xffffff alpha:0.4]];
        }
    }];
    //验证码是否可用
    RAC(self.getCode.titleLabel,text) = RACObserve(self.viewModel,phoneCodeText);
    RAC(self.getCode, enabled) = self.viewModel.getCodeSignal;
//    [self.viewModel.getCodeSignal
//     subscribeNext:^(NSNumber * usernameIsValid) {
//         if(usernameIsValid.boolValue){
//             [self.getCode setTitleColor:[UIColor colorWithHex:0x21C7B6] forState:UIControlStateNormal];
//         }else{
//             [self.getCode setTitleColor:[UIColor colorWithHex:0x777777] forState:UIControlStateDisabled];
//         }
//     }];
    
    [[self.codeText.rac_keyboardReturnSignal filter:^BOOL(id value) {
        @strongify(self)
        return self.LoginTo.enabled;
    }] subscribeNext:^(id x) {
        @strongify(self)
        [self.viewModel.loginCommand execute:nil];
    }];
    //点击获取验证码动作
    [[self.getCode
      rac_signalForControlEvents:UIControlEventTouchUpInside]
     subscribeNext:^(id x) {
         @strongify(self)
         [self.viewModel.phoneCodeCommand execute:nil];
     }];

    //点击登录动作
    [[self.LoginTo
      rac_signalForControlEvents:UIControlEventTouchUpInside]
     subscribeNext:^(id x) {
         @strongify(self)
         [self.viewModel.loginCommand execute:nil];
         [self addUserBehaviourString:@"Event_Login"];
     }];
    
    [[self.weixinButton rac_signalForControlEvents:UIControlEventTouchUpInside]
     subscribeNext:^(id x) {
         @strongify(self)
         [self otherLogin:1];
     }];
    
    [[self.qqButton rac_signalForControlEvents:UIControlEventTouchUpInside]
     subscribeNext:^(id x) {
         @strongify(self)
         [self otherLogin:2];
     }];
//
//    [[self.sinaButton rac_signalForControlEvents:UIControlEventTouchUpInside]
//     subscribeNext:^(id x) {
//         @strongify(self)
//         [self otherLogin:3];
//     }];
}

#pragma mark --

- (PreLoginViewModel*)viewModel{
    if (!_viewModel) {
        _viewModel = [[PreLoginViewModel alloc] initWithViewController:self];
    }
    return _viewModel;
}


/**
 *  第三方登录
 *
 *  @param otherTppe 1：微信，2：QQ,3:新浪微博
 */
- (void)otherLogin:(int)otherTppe{
    
    NSString *platformName = nil;
    
    if (otherTppe==1) {
        platformName = [UMSocialSnsPlatformManager getSnsPlatformString:UMSocialSnsTypeWechatSession];
    }else{
        platformName = [UMSocialSnsPlatformManager getSnsPlatformString:UMSocialSnsTypeMobileQQ];
    }
    if (platformName) {
        [UMSocialControllerService defaultControllerService].socialUIDelegate = self;
        UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:platformName];
        snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
            //           获取微博用户名、uid、token、第三方的原始用户信息thirdPlatformUserProfile等
            if (response.responseCode == UMSResponseCodeSuccess) {
                UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary] valueForKey:platformName];
                
                [[self.viewModel otherLoginCommand] execute:snsAccount];
            }
        });
    }
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
